﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

using System.Xml;
using FetchAndProcess.Models;
using WebDUPlugIn.ConfigAndModels;
using HtmlAgilityPack;
using WebDUPlugIn.WebDUReporter;


namespace WebDUPlugIn.Processors
{
    public class PropData
    {
        public string Name { get; set; }        
        public string type { get; set; }
        public string streetname { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string zipcode { get; set; }
        public string PhoneNumber { get; set; }

        public PropData()
        {
            Name = "";
            type = "";
            streetname = "";
            City = ""; State = ""; zipcode = ""; PhoneNumber = "";
        }
        public override string ToString()
        {
            string str = String.Format("{0};{1};{2};{3};{4};{5}", type, Name, streetname, City, State, zipcode);
            return str;
        }
    }


    public class TADVExtract : ProcessInterface
    {

        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static int _entityCount=0;

        public bool processrawData(string fetcherName, object rawDatatoProcess, ProcessorConfigBaseRec processorConfigObject)
        {
            // Process Data 

            var processRec = rawDatatoProcess as DocumentToProcess;
            if (processRec != null)
            {
                log.DebugFormat(" Process Data for   URI : {0} ", processRec.processedUri);
            }

            // Check URL for Hotel_Review or Retaurant Review work 
            var prop = getHotelDetailsFromURL(processRec);
            if (prop != null)
            {
                string str = prop.ToString();
                log.DebugFormat(" Entity Data Extracted  for URI : {0}  DATA : {0} ", processRec.processedUri,str);
                ExtractedElements.AddDataToDictionary(processRec.processedUri.AbsoluteUri, str);
                
                {
                    ++_entityCount;
                    if (_entityCount % 10 == 0)
                    {
                        _entityCount = 0;
                        ExtractedElements.DumpDictionarytoFile();
                    }
                }
            }

            return true;
        }

        //Read processor specific configuration.. 
        public ProcessorConfigBaseRec getConfiguration(XmlNode processorNode)
        {
            return null;
        }

        #region PRIVATE_HELPERS
        private const string HotelNameIndexStr = "HotelName";
        private const string ReviewTypeStr     = "ReviewType";
        private const string CityStr = "CityState";


        private const string xpathName = "//*[@id='HEADING' and @property='v:name']";
        private const string xpathStreet = "//*[@property='v:street-address']";
        private const string xpathCity = "//*[@property='v:locality']";
        private const string xpathState = "//*[@property='v:region']";
        private const string xpathZipCode = "//*[@property='v:postal-code']";
        private const string xpathPhoneNum = "//*[@class='sprite-greenPhone fl icnLink']";



        /// <summary>
        /// Get Property Details
        /// </summary>
        /// <param name="processRec"></param>
        private  PropData getHotelDetailsFromURL(DocumentToProcess processRec)
        {
            var uri = processRec.processedUri; 
            string pattern1 = @"(?<ReviewType>(Hotel_Review|Restaurant_Review))-\w+-\w+-\w+-(?<HotelName>\w+)-(?<CityState>\w+)\S*";
            Regex g = new Regex(pattern1);
            Match m = g.Match(uri.LocalPath);
            PropData property = null;

            if (m.Success)
            {
               // get data from Groups 
                property = new PropData();
                property.Name = m.Groups[HotelNameIndexStr].Value;
                //property.CityState = m.Groups[CityStr].Value;
                property.type = m.Groups[ReviewTypeStr].Value.Replace("_Review", "");

                // Process HTML Doc Now 
                var doc = processRec.htmlDoc;
                //1. Extract Name 
                property.Name = FillValueFromHtmlDoc(doc, xpathName);
                //2. Extract Address 
                property.streetname = FillValueFromHtmlDoc(doc, xpathStreet);
                property.City = FillValueFromHtmlDoc(doc, xpathCity);
                property.State = FillValueFromHtmlDoc(doc, xpathState);
                property.zipcode = FillValueFromHtmlDoc(doc, xpathZipCode);


                //3. Extract Phone Number 
                property.PhoneNumber = "";
                //4. Extract WebSite
            }

            return property;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="xpathStr"></param>
        /// <param name="fillVar"></param>
        private string   FillValueFromHtmlDoc(HtmlDocument doc, string xpathStr)
        {
            string fillVar = "";
            var htmlNameNode = doc.DocumentNode.SelectSingleNode(xpathStr);
            if (htmlNameNode != null)
            {
                fillVar = htmlNameNode.InnerText;
            }
            return fillVar;
        }

        #endregion
    }
}
